package cvo.chess.client.entities.armies.pieces;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;

import cvo.chess.client.entities.IGameFacade;
import cvo.chess.client.entities.chessboard.ChessboardCoordinate;
import cvo.chess.client.entities.chessboard.IChessboardCoordinate;
import cvo.chess.client.entities.game.Army;
import cvo.chess.client.entities.game.Piece;

public class Queen extends Piece {

	public Queen(IGameFacade gf, Army army) {
		super(gf, army);
	}

	public Queen(IGameFacade gf, Army army, String name) {
		super(gf, army, name);
	}

	@Override
	public List<ChessboardCoordinate> getPossibleMoves() throws Exception {
		List<ChessboardCoordinate> possibleMoves = new ArrayList<ChessboardCoordinate>();
	
		possibleMoves.addAll((iterateDirection(0, -1)));
		possibleMoves.addAll((iterateDirection(-1, 0)));
		possibleMoves.addAll((iterateDirection(0, +1)));
		possibleMoves.addAll((iterateDirection(+1, 0)));
		possibleMoves.addAll((iterateDirection(-1, -1)));
		possibleMoves.addAll((iterateDirection(-1, +1)));
		possibleMoves.addAll((iterateDirection(+1, -1)));
		possibleMoves.addAll((iterateDirection(+1, +1)));
//		Window.alert(possibleMoves.toString());
		return possibleMoves;
	}

	//returns true if the piece at position is not from the same army.
	
	private boolean isEnemy(ChessboardCoordinate position) {
		return (!gf.getPieceAt(position.getA1Notation()).getColor().equals(this.getColor()));
	}

	private boolean isEmptyPosition(ChessboardCoordinate position) {
		return (gf.getPieceAt(position.getA1Notation()) == null);
	}

	// functie omdat functie in ChessboardCoordinate nog niet implemented is.
	private boolean isOnBoard(int x, int y) {
		return (x >= 0 && x <  (gf.getBoard().getWidth()))	&& (y >= 0 && y < (gf.getBoard().getHeight()));
	}

	private List<ChessboardCoordinate> iterateDirection(int xMove, int yMove) throws Exception {
		
		List<ChessboardCoordinate> possibleMoves = new ArrayList<ChessboardCoordinate>();

		IChessboardCoordinate currentPosition = gf.getPositionOfPiece(this);

		int xNew = currentPosition.getCol() + xMove;
		int yNew = currentPosition.getRow() + yMove;
		

		for (int x = xNew, y = yNew; isOnBoard(x, y); x = x + xMove, y = y + yMove) {
			
			if (isOnBoard(x, y)) {
				ChessboardCoordinate possiblePosition = new ChessboardCoordinate(gf.getBoard(), x, y);
				if (isEmptyPosition(possiblePosition)){
					possibleMoves.add(possiblePosition);
					
				}else{
					if(isEnemy(possiblePosition)){
						possibleMoves.add(possiblePosition);
						return possibleMoves;
						}else{
							return possibleMoves;
						}
				}
			}
		}
		
		return possibleMoves;
	
	}
}
